<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    #canvas {
      margin: 12em;
      background-color: gray;
    }
  </style>
</head>
<body>
  <canvas height="400" id="canvas" width="400"></canvas>
  <script src="../lib/index.js"></script>
  <script>
    const canvas = document.getElementById('canvas');
    const gl = canvas.getContext('webgl');
    const  vshaderSource = `
    attribute vec4 aPosition;
      void main() {
        gl_Position = aPosition;
        gl_PointSize = 30.0;
      }
    `
    const fshaderSource = `
    void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
      }
    `
    const program = initShaders(gl, vshaderSource, fshaderSource)

    const aPosition = gl.getAttribLocation(program, 'aPosition') // 获取aPosition变量
    // gl.vertexAttrib1f(aPosition, 0.0) // 设置aPosition的值
    // gl.drawArrays(gl.POINTS, 0, 1) //


    const points = []
    canvas.onmousemove = (ev) => {
      //该坐标系是：当前鼠标相对于浏览器窗口左上角的坐标
      const x = ev.clientX
      const y = ev.clientY
      console.log(x, y)

      //  转换坐标: 转换成canvas的坐标系
      const domPosition = ev.target.getBoundingClientRect() // 表示 canvas 元素在视口中的位置。

      //  转换成canvas的坐标系，当前鼠标相对于canvas左上角的坐标
      let  domx =  x - domPosition.left
      let  domy =  y - domPosition.top

      // 转换成webgl的坐标系(-1,1)
      const glx = (domx - canvas.width/2)/(canvas.width/2)
      const gly = (canvas.height/2 - domy)/(canvas.height/2)
      points.push({
        x: glx,
        y: gly
      })
      for (let i = 0; i < points.length; i++) {
        gl.vertexAttrib2f(aPosition, points[i].x, points[i].y)
        gl.drawArrays(gl.POINTS, 0, 1)
      }
    }

  </script>
</body>
</html>
